<template>
  <view class="album-detail">
    <!-- 顶部封面区域 -->
    <view class="album-header">
      <image 
        :src="album.coverUrl || '/static/default-album.png'" 
        mode="aspectFill" 
        class="album-cover"
      ></image>
      <view class="album-info">
        <view class="title-row">
          <text class="album-title">{{ album.title }}</text>
          <view v-if="album.status === 0" class="privacy-badge">
            <text>私密</text>
          </view>
        </view>
        <text class="photo-count">{{ album.photoCount || 0 }}张照片</text>
      </view>
      <!-- 编辑按钮 -->
      <view class="edit-btn" @click="goEdit">
        <text class="edit-icon">✏️</text>
      </view>
    </view>

    <!-- 照片网格 -->
    <scroll-view 
      class="photo-grid-container" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 加载中状态 -->
      <view class="loading-state" v-if="isLoading && !photos.length">
        <view class="loading-spinner">
          <u-loading-icon size="36" color="#3a8838"></u-loading-icon>
        </view>
        <text>加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else-if="!photos.length">
        <view class="empty-icon">🖼️</view>
        <text class="empty-text">暂无照片</text>
        <text class="empty-subtext">点击底部"上传照片"按钮添加照片</text>
      </view>

      <!-- 照片时间线视图 -->
      <view v-else class="timeline-view">
        <!-- 遍历时间分组 -->
        <view 
          class="time-group"
          v-for="(group, date) in groupedPhotos" 
          :key="date"
        >
          <!-- 时间标题 -->
          <view class="time-header">
            <text class="time-date">{{ formatGroupDate(date) }}</text>
            <text class="photo-count">{{ group.length }}张</text>
          </view>
          
          <!-- 照片网格 -->
          <view class="photo-grid">
            <view 
              class="photo-item"
              v-for="photo in group"
              :key="photo.id"
              @click="handlePhotoClick(photo, group)"
              @longpress="handlePhotoLongPress(photo, group)"
            >
              <image 
                :src="photo.url" 
                mode="aspectFill"
              ></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="loading-more" v-if="isLoading && photos.length">
        <view class="loading-spinner">
          <u-loading-icon size="24" color="#999"></u-loading-icon>
        </view>
        <text>加载中...</text>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-action-bar">
      <view class="action-btn upload" @click="uploadPhotos">
        <text class="upload-icon">⬆️</text>
        <text>上传照片</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getMyAlbums } from '@/api/album'
import request from '@/utils/request'
import { getImageBlob } from '@/utils/image.js'
import { formatDate } from '@/utils/date'

export default {
  data() {
    return {
      albumId: '',
      album: null,
      photos: [],
      page: 1,
      pageSize: 20,
      isLoading: false,
      isRefreshing: false,
      noMoreData: false,
      isLongPress: false,
      isFeatured: false
    }
  },
  computed: {
    // 按照上传日期对照片进行分组
    groupedPhotos() {
      const groups = {};
      
      if (!this.photos.length) return groups;
      
      // 按日期分组照片
      this.photos.forEach(photo => {
        // 获取日期部分（YYYY-MM-DD）
        const uploadDate = photo.uploadTime ? photo.uploadTime.split(' ')[0] : '未知日期';
        
        if (!groups[uploadDate]) {
          groups[uploadDate] = [];
        }
        
        groups[uploadDate].push(photo);
      });
      
      // 对分组进行排序（最新日期在前）
      const sortedGroups = {};
      Object.keys(groups)
        .sort((a, b) => new Date(b) - new Date(a))
        .forEach(key => {
          sortedGroups[key] = groups[key];
        });
      
      return sortedGroups;
    }
  },
  onLoad(options) {
    this.albumId = options.id
    this.isFeatured = options.isFeatured === '1'
    if (!this.albumId) {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    this.initData();
    
    // 监听照片上传完成事件
    uni.$on('photo:uploaded', this.handlePhotoUploaded);
    // 监听相册更新事件
    uni.$on('album:updated', this.handleAlbumUpdated);
  },
  onUnload() {
    // 移除事件监听
    uni.$off('photo:uploaded', this.handlePhotoUploaded);
    uni.$off('album:updated', this.handleAlbumUpdated);
  },
  methods: {
    // 处理照片上传完成事件
    handlePhotoUploaded(data) {
      console.log('收到照片上传事件:', data);
      if (data && data.albumId && data.albumId.toString() === this.albumId.toString()) {
        // 刷新相册和照片数据
        this.onRefresh();
      }
    },
    
    // 处理相册更新事件
    handleAlbumUpdated(data) {
      console.log('收到相册更新事件:', data);
      if (data && data.albumId && data.albumId.toString() === this.albumId.toString()) {
        // 刷新相册信息
        this.onRefresh();
      }
    },
    
    // 格式化分组日期显示
    formatGroupDate(dateStr) {
      if (dateStr === '未知日期') return dateStr;
      
      try {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        
        const weekAgo = new Date(today);
        weekAgo.setDate(weekAgo.getDate() - 7);
        
        const monthAgo = new Date(today);
        monthAgo.setMonth(monthAgo.getMonth() - 1);
        
        const date = new Date(dateStr);
        
        // 今天
        if (date.getTime() === today.getTime()) {
          return '今天';
        }
        
        // 昨天
        if (date.getTime() === yesterday.getTime()) {
          return '昨天';
        }
        
        // 本周
        if (date >= weekAgo && date < yesterday) {
          const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
          return days[date.getDay()];
        }
        
        // 本月
        if (date >= monthAgo && date < weekAgo) {
          return `${date.getMonth() + 1}月${date.getDate()}日`;
        }
        
        // 今年
        if (date.getFullYear() === today.getFullYear()) {
          return `${date.getMonth() + 1}月${date.getDate()}日`;
        }
        
        // 更早
        return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
      } catch (err) {
        return dateStr;
      }
    },
    
    // 初始化数据
    async initData() {
      this.isLoading = true;
      try {
        // 并行加载数据，提高效率
        await Promise.all([
          this.loadAlbumInfo(),
          this.loadPhotos()
        ]);
      } catch(error) {
        console.error('初始化数据失败:', error);
      } finally {
        this.isLoading = false;
      }
    },
    
    // 加载相册信息
    async loadAlbumInfo() {
      try {
        // 使用首页列表API获取相册信息而不是单独的详情API
        const result = await getMyAlbums();
        const albums = result.data?.records || [];
        // 从列表中找到当前相册
        const currentAlbum = albums.find(a => a.albumId.toString() === this.albumId.toString());
        
        if (currentAlbum) {
          // 确保有基本数据
          this.album = {
            albumId: currentAlbum.albumId,
            title: currentAlbum.title || '未命名相册',
            status: currentAlbum.status,
            photoCount: currentAlbum.photoCount || 0,
            description: currentAlbum.description || '',
            coverUrl: currentAlbum.coverUrl || ''
          };
          
          // 如果有封面照片但没有封面URL，尝试获取封面
          if (currentAlbum.coverPhoto && !currentAlbum.coverUrl) {
            try {
              // 等待封面加载完成
              const coverUrl = await getImageBlob(currentAlbum.coverPhoto);
              // 确保直接更新UI
              this.$nextTick(() => {
                this.album.coverUrl = coverUrl;
              });
            } catch (err) {
              console.error('加载封面失败:', err);
            }
          }
        } else {
          console.warn('在列表中未找到当前相册信息');
          // 设置默认值，避免UI显示空白
          this.album = {
            title: '未找到相册',
            photoCount: 0,
            status: 1
          };
        }
      } catch (error) {
        console.error('加载相册信息失败:', error);
        uni.showToast({
          title: '加载相册信息失败',
          icon: 'none'
        });
      }
    },
    
    // 加载照片
    async loadPhotos(isRefresh = false) {
      // 如果是初始加载，不设置loading状态，由initData统一管理
      const isInitialLoad = !isRefresh && this.photos.length === 0;
      
      if (isRefresh) {
        this.page = 1;
        this.noMoreData = false;
      }
      
      // 如果不是初始加载也不是刷新，且正在加载或已无更多数据，则返回
      if (!isInitialLoad && !isRefresh && (this.isLoading || this.noMoreData)) {
        return;
      }
      
      // 只有在非初始加载时才设置独立的loading状态
      if (!isInitialLoad) {
        this.isLoading = true;
      }
      
      try {
        // 调用照片分页API
        const params = {
          current: this.page,
          size: this.pageSize
        };
        
        // 使用 /v1/photo/album/{albumId} 接口获取相册照片
        const result = await request({
          url: `/v1/photo/album/${this.albumId}`,
          method: 'get',
          params
        });
        
        // 处理响应数据
        const photos = result.data?.records || [];
        console.log('获取到的照片数据:', photos);
        
        // 处理每个照片的URL
        for (const photo of photos) {
          try {
            photo.url = await getImageBlob(photo.photoPath);
            // 确保 id 字段存在，用于预览功能
            photo.id = photo.photoId;
          } catch (err) {
            console.error('加载照片失败:', err);
            photo.url = '';
          }
        }
        
        if (isRefresh) {
          this.photos = photos;
        } else {
          this.photos.push(...photos);
        }
        
        this.noMoreData = photos.length < this.pageSize;
        this.page++;
      } catch (error) {
        console.error('加载照片失败:', error);
        // 只有非初始加载的错误才提示
        if (!isInitialLoad) {
          uni.showToast({
            title: '加载照片失败',
            icon: 'none'
          });
        }
      } finally {
        // 只有非初始加载才在这里重置loading状态
        if (!isInitialLoad) {
          this.isLoading = false;
        }
        
        if (isRefresh) {
          this.isRefreshing = false;
        }
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      try {
        // 并行加载数据，提高效率
        await Promise.all([
          this.loadAlbumInfo(),
          this.loadPhotos(true)
        ]);
      } catch(error) {
        console.error('刷新数据失败:', error);
      } finally {
        this.isRefreshing = false;
      }
    },
    
    // 加载更多
    loadMore() {
      this.loadPhotos();
    },
    
    // 处理照片点击
    handlePhotoClick(photo, group) {
      console.log('点击照片:', photo);
      // 如果是长按，重置状态并返回
      if (this.isLongPress) {
        this.isLongPress = false;
        return;
      }
      
      // 点击跳转到详情页
      if (photo && photo.photoId) {
        console.log('跳转到照片详情，ID:', photo.photoId);
        uni.navigateTo({
          url: `/pages/photo/detail?id=${photo.photoId}`
        });
      } else {
        console.warn('照片缺少photoId:', photo);
      }
    },
    
    // 处理照片长按
    handlePhotoLongPress(photo, group) {
      this.isLongPress = true;
      this.previewPhoto(photo, group);
    },
    
    // 预览照片（长按时使用）
    previewPhoto(currentPhoto, photoGroup) {
      // 获取组内所有照片的URL
      const urls = photoGroup.map(p => p.url);
      // 找到当前照片的索引
      const currentIndex = photoGroup.findIndex(p => p.photoId === currentPhoto.photoId);
      
      uni.previewImage({
        urls,
        current: currentIndex
      });
    },
    
    // 上传照片
    uploadPhotos() {
      // 直接跳转到上传页面，将相册ID传过去
      uni.navigateTo({
        url: `/pages/photo/upload?albumId=${this.albumId}`
      });
    },
    
    // 跳转到编辑页
    goEdit() {
      uni.navigateTo({
        url: `/pages/album/edit?id=${this.albumId}`
      });
    }
  }
}
</script>

<style>
.album-detail {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.album-header {
  position: relative;
  height: 400rpx;
}

.album-cover {
  width: 100%;
  height: 100%;
}

.album-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  color: #fff;
}

.title-row {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.album-title {
  font-size: 36rpx;
  font-weight: bold;
}

.privacy-badge {
  margin-left: 20rpx;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.photo-count {
  font-size: 28rpx;
  opacity: 0.8;
}

.edit-btn {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.edit-icon {
  font-size: 32rpx;
}

.photo-grid-container {
  flex: 1;
  padding: 10rpx;
}

/* 时间线视图样式 */
.timeline-view {
  padding: 10rpx;
}

.time-group {
  margin-bottom: 30rpx;
}

.time-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 15rpx;
  border-bottom: 1rpx solid #eee;
}

.time-date {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.time-header .photo-count {
  font-size: 24rpx;
  color: #999;
  opacity: 1;
}

.photo-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 5rpx;
}

.photo-item {
  width: calc(33.33% - 10rpx);
  margin: 5rpx;
  aspect-ratio: 1;
  background-color: #fff;
  border-radius: 8rpx;
  overflow: hidden;
}

.photo-item image {
  width: 100%;
  height: 100%;
}

.bottom-action-bar {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
}

.action-btn text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.upload-icon {
  font-size: 28rpx;
}

.upload {
  background-color: #e8f5e9;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  margin-bottom: 10rpx;
}

.loading-image {
  width: 72rpx;
  height: 72rpx;
}

.loading-image-small {
  width: 48rpx;
  height: 48rpx;
}

.loading-state, .empty-state {
  padding: 100rpx 0;
  text-align: center;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  margin-top: 10rpx;
  display: block;
  font-size: 30rpx;
  color: #666;
}

.empty-subtext {
  margin-top: 10rpx;
  display: block;
  font-size: 26rpx;
  color: #999;
}

.loading-more {
  padding: 30rpx 0;
  text-align: center;
  color: #999;
  font-size: 24rpx;
}

.featured-grid {
  padding: 0;
  margin: 0;
  background: #f8f8f8;
}

.featured-grid .photo-item {
  margin: 0;
  border-radius: 0;
  box-shadow: none;
}

.featured-grid .photo-item image {
  border-radius: 0;
}

.featured-grid .photo-info {
  display: none;
}
</style> 